import * as zrender from 'zrender';

/**
 * 排班条组件
 * 负责渲染单个排班任务条
 */
export class ScheduleBar {
  private zr: any;
  private shift: Shift;
  private y: number;
  private personColumnWidth: number;
  private unitWidth: number;
  private barHeight: number;
  private barGroup: zrender.Group;

  constructor(
    zr: any,
    shift: Shift,
    _chartState: ChartState,
    y: number,
    personColumnWidth: number,
    unitWidth: number,
    barHeight: number,
  ) {
    this.zr = zr;
    this.shift = shift;
    this.y = y;
    this.personColumnWidth = personColumnWidth;
    this.unitWidth = unitWidth;
    this.barHeight = barHeight;
    this.barGroup = new zrender.Group();
  }

  /**
   * 渲染排班条
   */
  render() {
    this.barGroup.removeAll();

    // 计算排班条位置和尺寸
    const { x, width } = this.calculateBarPosition();

    // 绘制排班条背景
    this.drawBarBackground(x, width);

    // 绘制排班条文本
    this.drawBarText(x, width);

    // 绘制排班条边框
    this.drawBarBorder(x, width);

    // 添加到画布
    this.zr.add(this.barGroup);
  }

  /**
   * 计算排班条位置和尺寸
   */
  private calculateBarPosition() {
    const startX = this.personColumnWidth + this.shift.start * this.unitWidth;
    const width = this.shift.duration * this.unitWidth;

    return {
      x: startX,
      width,
    };
  }

  /**
   * 绘制排班条背景
   */
  private drawBarBackground(x: number, width: number) {
    // 留出边距
    const margin = 2;

    const background = new zrender.Rect({
      shape: {
        x: x + margin,
        y: this.y + margin,
        width: width - margin * 2,
        height: this.barHeight - margin * 2,
      },
      style: {
        fill: this.shift.fillColor || '#007bff',
        stroke: 'none',
      },
    });

    this.barGroup.add(background);
  }

  /**
   * 绘制排班条文本
   */
  private drawBarText(x: number, width: number) {
    const margin = 2;
    const textWidth = width - margin * 2;

    // 只有当宽度足够时才显示文本
    if (textWidth > 30) {
      const text = new zrender.Text({
        style: {
          text: this.shift.name,
          x: x + width / 2,
          y: this.y + this.barHeight / 2,
          verticalAlign: 'middle',
          fontSize: 10,
          fill: '#ffffff',
          fontWeight: 'bold',
        },
      });

      this.barGroup.add(text);
    }
  }

  /**
   * 绘制排班条边框
   */
  private drawBarBorder(x: number, width: number) {
    const margin = 2;

    const border = new zrender.Rect({
      shape: {
        x: x + margin,
        y: this.y + margin,
        width: width - margin * 2,
        height: this.barHeight - margin * 2,
      },
      style: {
        fill: 'none',
        stroke: '#ffffff',
        lineWidth: 1,
      },
    });

    this.barGroup.add(border);
  }

  /**
   * 更新排班条数据
   */
  update(shift: Shift, y: number) {
    this.shift = shift;
    this.y = y;
  }

  /**
   * 获取排班条位置信息
   */
  getBarBounds() {
    const { x, width } = this.calculateBarPosition();
    return {
      x,
      y: this.y,
      width,
      height: this.barHeight,
    };
  }
}
